local linksController = {}
local vaild = require 'library.vaild'
local db = require 'models.db'
local user = require 'library.user'
local helper = require 'library.helpers'
local page = require 'library.pageobj'

function linksController:index()
    local p = {}
    local page_params = {}
    page_params['page']=":page:"
    local get = self:getRequest():getParams()
   
    local links=db:new('links') 
    local pageobj = page:new(links:count(),15,tonumber(get['page']),helper:url('admin/links/index',page_params));
    local res = links:order('id desc'):limit(pageobj:limit()):get_list()

    p['page'] = pageobj;
    p['links'] = res;

   return self:display(p)
end

function linksController:create()
    local p = {
       url=helper:url('admin/links/store'),
       link={}
    }
    return self:display('admin.links/edit.html',p)
end

function linksController:store()
    local links=db:new('links')
    local post=self:getRequest():POST()

    local id=helper:intval(post['id'])
    local link={}
    if id>0 then
        link=links:where('id=?',id):get_one()
        if helper:is_empty_table(link) then
            return helper:show_msg('错误,没有找到记录',{url=helper:url('admin/links/index')});
        end
    end
    self:save(link)
end
function linksController:save(data)

    local post=self:getRequest():POST()
    local vaild_my=vaild:new(post);
    vaild_my:add('name','required','title error');
    vaild_my:add('link','required','link error');

    local now=ngx.localtime()

    if vaild_my:run() then
        local links=db:new('links')
        if helper:is_empty_table(data) then
            data['created_at']=now
        end
        
        data['name']=post['name']
        data['link']=post['link']
        data['is_show']=helper:intval(post['is_show'])
        data['updated_at']=now

        local ret=links:replace(data)

        if ret then
            self:redirect(helper:url('admin/links/index'))
        end
    end
    helper:show_msg(1,'保存失败',{url=helper:url('admin/links/index')});
end


function linksController:edit()
    local p = {}
    local get = self:getRequest():getParams()
    local id=tonumber(get['id']) 
    local links=db:new('links') 

    p['link']=links:where("id=?",id):get_one()

    if p['link'] then
        p['url']=helper:url('admin/links/store')
        return self:display(p)
    else
        return helper:show_msg(1,'错误,没有找到记录',{url=helper:url('admin/links/index')});
    end
end

function linksController:destroy()
    local p = {}
    local post=self:getRequest():POST()

    if helper:is_natural_no_zero(post['id']) then
        local links=db:new('links') 
        links:where("id=?",post['id']):delete()
        self:redirect(helper:url('admin/links/index'))
    end
    return helper:show_msg(1,'错误,没有找到记录',{url=helper:url('admin/links/index')});
end

return linksController
